using System;
using System.IO;
using Microsoft.Isam.Esent.Collections.Generic;

namespace SG.Lang.Dry.Persistance
{
    public static class Repository<TElementRecord>
        where TElementRecord : struct
    {
// ReSharper disable StaticFieldInGenericType
        private static readonly PersistentDictionary<Guid, TElementRecord> Elements;
// ReSharper restore StaticFieldInGenericType

        static Repository()
        {
            var @base = Repository.BaseDirectory;
            if (@base == null)
                return;

            Repository.OnApplicationExit += Repositry_OnApplicationExit;
            var type = typeof (TElementRecord).Name;
            Elements = new PersistentDictionary<Guid, TElementRecord>(Path.Combine(@base, type));     
        }

        public static bool TryGet(ref Guid guid, out TElementRecord element)
        {
            if (Elements != null)
                return Elements.TryGetValue(guid, out element);
            
            element = default(TElementRecord);
            return false;
        }

        public static void Add(ref Guid guid, ref TElementRecord element)
        {
            if (Elements == null) return;
            
            Elements[guid] = element;
        }

        static void Repositry_OnApplicationExit(object sender, EventArgs e)
        {
            if (Elements == null)
                return;

            Elements.Dispose();
        }
    }
}